$(function () {
  init()

  account.forceLogin = false
  account.getUserInfo((err, userInfo) => {
    if (!err && userInfo && userInfo.shareFlag) {
      $('#switch-account').text('切换账号')
      window.activeShare(userInfo.shareFlag)
    }
    if (gid || !err) {
      getGroupBuyInfo(gid)
    }
    var weChatCode = utils.getQueryString('code')
    var authCallback = account.getAuthCallback()
    if (!err && weChatCode && authCallback) {
      try {
        eval(authCallback)
      } catch (e) {
        console.log(e)
      }
    }
    account.setAuthCallback()
  })

  function getGroupBuyInfo () {
    account.ajax($.extend({
      type: 'POST',
      path: `/s/products/${productId}/buying`,
      success: result => {
        console.log(result)
        // //已经开团
        resetShareDetail(result.id)
        window.creator = result.creatorId
        window.winningUserId = result.winningUserId
        setGroupBuyStatus(result, true)
        getGroupBuyerList(result.buyers.toString())
      },
      error: err => setGroupBuyStatus(err, false)
    }, !gid ? {} : {
      auth: false,
      data: {groupBuyingId: encodeURIComponent(decodeURIComponent(gid))}
    }))
  }

  function setUserList (userList) {
    console.log(userList)
    $('.user-list').empty()
    const defaultAvatar = `${CDN_RESOURCE}/mobile/campaign/lottery/img/default.png`
    const nullAvatar = `${CDN_RESOURCE}/mobile/campaign/lottery/img/avatar.png`
    userList.sort(user => user.id === creator ? -1 : 1)
    for (let i = 0; i < 8; i++) {
      const user = i < userList.length ? userList[i] : false
      const captain = i === 0 ? 'captain' : ''
      const win = user && user.id === winningUserId ? 'win' : ''
      const avatar = user ? (user.avatar ? user.avatar : nullAvatar) : defaultAvatar
      $('.user-list').append(`
        <div class="user-item ${captain} ${win}">
          <img class="avatar" src="${avatar}" onerror="this.src='${defaultAvatar}'">
        </div>
      `)
    }
  }

  function setCountDown (endAt) {
    setInterval(function () {
      var timestamp = parseInt(new Date().getTime() / 1000)
      var timeDiff = endAt - timestamp
      var day = Math.floor(timeDiff / 60 / 60 / 24)
      var hour = Math.floor(timeDiff / 60 / 60 % 24)
      var min = Math.floor(timeDiff / 60 % 60)
      var sec = Math.floor(timeDiff % 60)

      document.getElementById('hour').innerText = hour >= 0 && hour <= 9 ? '0' + hour : hour
      document.getElementById('min').innerText = min >= 0 && min <= 9 ? '0' + min : min
      document.getElementById('sec').innerText = sec >= 0 && sec <= 9 ? '0' + sec : sec
    }, 1000)
  }

  function setGroupBuyCountDown (status, endAt) {
    $('.count-down').hide()
    if (starCount) clearInterval(starCount)
    if (status == 0) {
      starCount = setInterval(function () {

        var timestamp = Date.parse(new Date())
        if (timestamp >= endAt) {
          // 团购已经结束
          // $('.count-down').text('该团购已经到期!')
          // $('.count-down').show()
          clearInterval(starCount)

        } else if (timestamp < endAt) {
          var timeDiff = endAt - timestamp
          var day = Math.floor(timeDiff / 1000 / 60 / 60 / 24)
          var hour = Math.floor(timeDiff / 1000 / 60 / 60 % 24)
          var min = Math.floor(timeDiff / 1000 / 60 % 60)
          var sec = Math.floor(timeDiff / 1000 % 60)

          if (day < 10) {
            day = '0' + day
          }
          if (hour < 10) {
            hour = '0' + hour
          }
          if (min < 10) {
            min = '0' + min
          }
          if (sec < 10) {
            sec = '0' + sec
          }

          $('.count-down #day').text(day)
          $('.count-down #hour').text(hour)
          $('.count-down #min').text(min)
          if (day > 0) {
            $('.count-down #sec').hide()
            $('.count-down .colon').last().hide()
          } else {
            $('.count-down #day').hide()
            $('.count-down .colon').first().hide()
            $('.count-down #sec').text(sec)
          }
          $('.count-down').show()
        }
      }, 1000)

    } else if (status == 1) {
      // $('.count-down').text('已成团')
      // $('.count-down').show()
    } else {
      // $('.count-down').text('已过期')
      // $('.count-down').show()
    }

  }

  function campaignTimeStatus () {
    return (new Date).getTime() / 1000 <= campaignEnd
  }

  function setGroupBuyStatus (gpDetail, status) {

    if (!gpDetail || !gpDetail.id) return

    //  status: 1->已报名 2->未报名

    //  alert(groupBuyTimeStatus(gpDetail.endAt) + '-'  + campaignTimeStatus());

    var currentBuyerId = 0
    if (JSON.parse(window.localStorage.getItem(account.userInfoKey)) !== null) {
      currentBuyerId = JSON.parse(window.localStorage.getItem(account.userInfoKey)).id
    }

    var inGroup = gpDetail.buyers && gpDetail.buyers.indexOf(currentBuyerId) >= 0

    var cStatus = campaignTimeStatus()

    var endAt1 = new Date().getTime() / 1000 + 1000
    var endAt2 = new Date().getTime() / 1000 - 1000

    //status = true;
    //cStatus = true;
    //inGroup = true;

    // 组团中
    //gpDetail = { id: 1, status: 2, buyerCount: 2, endAt: endAt1, buyers: [9]};
    // 团成功
    //gpDetail = { id: 1, status: 1, buyerCount: 4, endAt: endAt2, buyers: [7,8,9,27]};
    // 团过期
    //gpDetail = { id: 1, status: 2, buyerCount: 4, endAt: endAt2, buyers: [9]};

    setGroupBuyCountDown(gpDetail.status, gpDetail.endAt * 1000)
    if (status) {
      if (gpDetail.status === 0) {
        if (inGroup) displayGroupBuyStatus(2, gpDetail.buyerCount)
        else displayGroupBuyStatus(8, gpDetail.buyerCount)
      } else if (gpDetail.status === 1) {
        if (inGroup) displayGroupBuyStatus(1)
        else {
          if (cStatus) displayGroupBuyStatus(5)
          else displayGroupBuyStatus(7)
        }
      } else {
        if (cStatus) {
          if (inGroup) displayGroupBuyStatus(4)
          else displayGroupBuyStatus(6)
        } else {
          if (inGroup) displayGroupBuyStatus(3)
          else displayGroupBuyStatus(7)
        }
      }
    }
  }

  function displayGroupBuyStatus (status, buyerCounter) {
    console.log(status)
    switch (status) {
      case 1:
        // 团购成功( 已报名 已成团 活动时间未到期 )
        $('.group-buy-status').text('当前团购成功')
        if (new Date().getTime() > 1539187199000) $('.buy').text('活动已结束')
        else $('.buy').text('本团已开奖，重新开团拼手气！')
        groupBuyStatus = 1
        // 👆👆👆  跳转到开奖页面，上述文字不需要
        window.location.href = resultUrl
        break
      case 2:
        // 尚未成团 (已报名 团没有满 团购时间未到期 活动时间还没到期  )
        $('.group-buy-status').html(`已有<span class="red">${buyerCounter}</span>人参团，仅差<span class="red">${8 - buyerCounter}</span>人即可马上拿奖！`)
        $('.buy').text('马上邀请好友，组团拼手气')
        groupBuyStatus = 2
        break
      case 3:
        // 活动已结束( 已报名 团没有满 团购时间到期 活动时间已到期)
        $('.group-buy-status').text('很遗憾，未能成功组团，活动已结束')
        if (new Date().getTime() > 1539187199000) $('.buy').text('活动已结束')
        else $('.buy').text('活动已结束')
        groupBuyStatus = 3
        break
      case 4:
        //很遗憾( 已报名 团没有满 团购时间到期 活动时间未到期)
        $('.group-buy-status').text('很遗憾，未能组团成功，请重新开团')
        if (new Date().getTime() > 1539187199000) $('.buy').text('活动已结束')
        else $('.buy').text('重新开团')
        groupBuyStatus = 4
        break
      case 5:
        // (👈👈👈 点击进入后为 分享后的页面）
        $('.group-buy-step4').addClass('active')
        // 该团已满，重新开团( 未报名 团已满 活动时间未到期 )
        $('.group-buy-status').text('')
        if (new Date().getTime() > 1539187199000) $('.buy').text('活动已结束')
        else $('.buy').text('本团已开奖，重新开团拼手气！')
        groupBuyStatus = 5
        break
      case 6:
        //请重新开团(  未报名 团没有满 团购时间已经到期 活动时间未到期)
        $('.group-buy-status').text('该团已结束，请重新开团')
        if (new Date().getTime() > 1539187199000) $('.buy').text('活动已结束')
        else $('.buy').text('重新开团拼手气')
        groupBuyStatus = 6
        break
      case 7:
        //活动已结束( 未报名 活动时间到期 )
        $('.group-buy-status').text('活动已结束')
        if (new Date().getTime() > 1539187199000) $('.buy').text('活动已结束')
        else $('.buy').text('活动已结束')
        groupBuyStatus = 7
        break
      case 8:
        //参加活动( 未报名 团购活动没有满 活动时间未到期 )
        $('.group-buy-status').html(`已有<span class="red">${buyerCounter}</span>人参团，仅差<span class="red">${8 - buyerCounter}</span>人即可马上拿奖！`)
        $('.buy').text('我要参团，拼手气拿课时')
        groupBuyStatus = 8
        break
      default:

    }
  }

  function getGroupBuyerList (ids) {
    account.ajax({
      auth: false,
      type: 'GET',
      path: '/s/students/socials',
      data: {ids},
      success: setUserList,
      error: err => utils.toastAlert(err.message)
    })
  }

  function resetShareDetail (_gid) {
    window.gid = _gid
    console.log(`reset_gid=${gid}`)
    account.getUserInfo((err, result) => {
      if (!err && utils.isWeChat()) window.activeShare(result.shareFlag)
    })
  }

  function getAvatar (avatar) {
    return avatar || `${CDN_RESOURCE}/img/mobile/campaign/doubleEleven/pic_avatar_boy.png`
  }

  function submitOrder () {
    account.setAuthCallback('submitOrder()')
    account.forceLogin = true
    //提交订单久趣后台
    account.getUserInfo((err, userInfo) => {
      if (err) {
        utils.toast(err.message)
      } else {
        $('#switch-account').text('切换账号')
        if (utils.isWeChat()) window.activeShare(userInfo.shareFlag)
        const payChannel = utils.isWeChat() ? 'weixin' : 'alipay'
        account.ajax({
          type: 'GET',
          path: '/s/customers/' + window.localStorage.getItem(account.openId) + '/status',
          success: function (status) {
            account.ajax({
              type: 'POST',
              path: '/s/bills',
              data: {
                productId,
                payChannel,
                returnUrl: status.subscribe ? `${campUrl}${Math.ceil(Math.random() * 100)}` : `${verifyUrl}`,
                tradeType: 'JSAPI',
                openId: window.localStorage.getItem(account.openId),
                groupBuyingId: groupBuyStatus === 5 ? '' : encodeURIComponent(decodeURIComponent(gid))
              },
              success: function (data) {
                //唤起微信支付
                if (data.status !== 'error') {
                  if (utils.isWeChat()) {
                    const jsApiParameters = JSON.parse(data.jsApiParameters)
                    jsApiParameters.redirect = status.subscribe ? `${campUrl}${Math.ceil(Math.random() * 100)}` : `${verifyUrl}`
                    wxconfig.pay(data.bill_id, productId, jsApiParameters, encodeURIComponent(campUrl))
                  } else {
                    window.location.href = data.url
                  }
                } else {
                  utils.toast('下单失败，请重试')
                }
              },
              error: err => {
                if (err.code === 'product.rejected.by.bought.products') {
                  utils.toast('您已经参加活动')
                  getGroupBuyInfo()
                }
              }
            })
          },
          error: err => {
            utils.toast(err.message)
          }
        })
      }
    })
  }

  $('.rule').off('click').on('click', () => {
    utils.info('奖品说明', '1.奖品课时为四人班课时，有效期30天，添加【久趣英语服务号】即可预约上课。 <br/>2.参加活动的孩子不需要同一英语水平，抽奖成功，会重新进行分级上课。')
  })

  $('.buy').off('click').on('click', () => {
    if ($('.buy').text() === '活动已结束') return
    if (groupBuyStatus === 3 && groupBuyStatus === 7) {
      window.location.href = '/wx'
    } else if (groupBuyStatus === 2 || groupBuyStatus === 1) {
      $('.share-mask').fadeIn()
    } else {
      submitOrder($(this).attr('data-field'))
    }
  })

  // 隐藏分享
  $('.share-mask').off('click').on('click', e => {
    $('.share-mask').fadeOut()
  })
})

function init () {
  window.campaign = 'lottery'
  window.productId = window.campaignProduct
  window.campUrl = `${window.location.protocol}//${window.location.host}/wx/${campaign}`
  window.verifyUrl = `${campUrl}/verifypayment`
  window.resultUrl = `${campUrl}/result`
  window.avPrefix = 'p008'
  window.analytics = AV.analytics({
    appId: 'antYy9lOFi5mkU9QKjtYmRLM-gzGzoHsz',
    appKey: 'jqyWxLyobpsmdwsJddJlDheb',
    channel: utils.isWeChat() ? 'weixin' : ''
  })
  window.wxconfig = new WxConfig(wechatConfig, campaign)
  window.account = new Account()
  window.campaignEnd = 1541001599
  window.starCount = 0
  window.groupBuyStatus = 0
  getGId()
  setShare()
  getChannel()
  analytics.send({
    event: `${avPrefix}_open`,
    attr: {gid}
  })
}

function getGId () {
  let state = utils.getUrlParam('state') || ''
  let gid = utils.getUrlParam('_gid') || utils.getUrlParam('gid') || state.replace('gid_', '')
  console.log(`gid=${gid}`)
  window.gid = gid
  return gid
}

function getChannel () {
  if (!utils.getUrlParam('_c')) {
    const QKidsChannel = JSON.parse(window.localStorage.getItem('QKidsChannel'))
    if (!(QKidsChannel && QKidsChannel.expires > new Date().getTime() / 1000)) {
      window.localStorage.setItem('QKidsChannel', JSON.stringify({
        rawData: `${campaign}_share`,
        expires: new Date().getTime() / 1000 + 24 * 3600
      }))
    }
  }
}

function setShare () {
  window.shareFlag = ''
  window.shareMsg = shareFlag => {
    return {
      title: '【久趣福利】1元抢3节北美外教课！',
      desc: '100%北美外教在线教学，让孩子爱上英语！',
      link: `${campUrl}${Math.ceil(Math.random() * 100)}?_c=${campaign}&_r=${shareFlag}&_gid=${gid}`,
      imgUrl: 'https://static-app.97kid.com/site-student/public/mobile/campaign/lottery/img/share.jpg',
      success: target => {
        analytics.send({
          event: `${avPrefix}_share_success`,
          attr: {target}
        })
      }
    }
  }
  window.activeShare = shareFlag => {
    console.log(shareMsg(shareFlag))
    if (utils.isWeChat()) window.shareFlag = shareFlag || ''
    wxconfig.activeShare(shareFlag, '', shareMsg(shareFlag))
  }
}